<?php

// $Id$

require_once(TANGRA_MAIN_DIR.'web_site/web_site.class.php');

require_once(TANGRA_MAIN_DIR.'exceptions/tangra_module_exception.class.php');


class Web_Site_Vanilla extends Web_Site {
	public function init() {
		$this->detect_current_language();
	}


	protected function handle_exception(Exception $e) {
		if ($this->_config->get_log_exceptions()) {
			$context_file = '';
			if ($this->_config->get_save_context_on_exception()) {
				$context_file = $this->write_context($this->_config->get_debug_dir(), $this->get__context());
			}

			$this->log_exception($this->_config->get_logs_dir().$this->_config->get_exceptions_log_file(), $e, $context_file);
		}

		parent::handle_exception($e);
	}


	protected function write_context($dir, Web_Context $context) {
		$context_file = tempnam($dir, "context_");

		$s = serialize($context);
		file_put_contents($context_file, $s);

		@chmod($context_file, 0660);

		return $context_file;
	}


	protected function log_exception($file, Exception $e, $context_file = NULL) {
		
		error_log(date('Y-m-d H:i:s').' +++ Exception. IP: '.$_SERVER['REMOTE_ADDR']."\n", 3, $file);
		error_log($_SERVER['SERVER_PROTOCOL'] . ' ' . $_SERVER['SERVER_NAME'] . ' ' . $_SERVER['SERVER_PORT'] . 
						' ' .$_SERVER['REQUEST_URI'] . "\n", 3, $file);
		if ($e instanceof Tangra_Exception) {
			error_log($e->get_original_msg()."\n", 3, $file);
		}

		error_log($e->getMessage()."\n", 3, $file);
		if ($context_file) {
			error_log('Context: '.$context_file."\n", 3, $file);
		}
		error_log("\n\n", 3, $file);
		@chmod($file, 0660);
	}


	protected function detect_current_language() {
		$context = $this->get__context();

		/*
			First checking if current_language is false. If not false then obviously some
			other module (more likely on boot time) has already detected current language so
			we don't want to everwrite it.
		*/
		if (!$this->_config->get_current_language()) {
			if ($context->exists_in_pi('_lang')) {
				$lang = $context->get_from_pi('_lang');
				if (in_array($lang, $this->_config->get_available_languages_arr())) {
					$this->_config->set_current_language($lang);
				} else {
					$this->_config->set_current_language($this->_config->get_default_language());
				}
			} else {
				$this->_config->set_current_language($this->_config->get_default_language());
			}
		}
	}
}




